//
//  InforViewController.m
//  美食百科
//
//  Created by dllo on 16/1/28.
//  Copyright © 2016年 doll. All rights reserved.
//

#import "InforViewController.h"
#import "NewWorking.h"
#import "AssessTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "ClassModel.h"
#import "ContentTableViewCell.h"
#import "LookTableViewCell.h"
#import "MoreInforViewController.h"
#import "CarouselModel.h"
#import "CollectModel.h"
#import "DataBaseHandle.h"
#import "Reachability.h"
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
@interface InforViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)UIImageView *imageView;
@property(nonatomic,retain)UILabel *nameLabel;
@property(nonatomic,retain)UILabel *calLabel;
@property(nonatomic,retain)UILabel *appendLabel;

@property(nonatomic,retain)UIView *lineView;
@property(nonatomic,retain)UIButton *calButton;
@property(nonatomic,retain)UIButton *jouleButton;
@property(nonatomic,retain)UITableView *inforView;
@property(nonatomic,copy)NSString *assess;
@property(nonatomic,copy)NSString *light;
@property(nonatomic,retain)NSMutableArray *array;
@property(nonatomic,retain)NSArray *titles;
@property(nonatomic,retain)NSMutableArray *gram;
@property(nonatomic,copy)NSString *calory;
@property(nonatomic,copy)NSString *protein;
@property(nonatomic,copy)NSString *fat;
@property(nonatomic,copy)NSString *carbohydrate;
@property(nonatomic,copy)NSString *fiber_dietary;

//@property(nonatomic,copy)NSMutableAttributedString *calString;
@property(nonatomic,assign)NSInteger cal;


@property(nonatomic,retain)ClassModel *classes;

@property(nonatomic,retain)CollectModel *collect;

@property(nonatomic,assign)BOOL YN;
@property(nonatomic,retain)UIBarButtonItem *rightItem;

@property(nonatomic,assign)NSInteger calNumber;
@end

@implementation InforViewController
- (void)dealloc
{
    [_imageView release];
    [_nameLabel release];
    [_calLabel release];
    [_appendLabel release];
    [_lineView release];
    [_calButton release];
    [_jouleButton release];
    [_inforView release];
    [_assess release];
    [_light release];
    [_array release];
    [_titles release];
    [_gram release];
    [_calory release];
    [_protein release];
    [_fat release];
    [_carbohydrate release];
    [_fiber_dietary release];
    [_classes release];
    [_collect release];
    [_rightItem release];

    [_classModel release];
    [_name release];
    [_left release];
    [_carouse release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // self.view.backgroundColor = [UIColor whiteColor];
    NSLog(@"🌲%ld",self.number);
 // NSInteger result = [[DataBaseHandle shareDataBaseHandle]createTable];

    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.calNumber = 0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, kWidth, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self.view addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, kWidth, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

    UIBarButtonItem *leftItemFirst = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-zuojiantou-3"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    
    
    
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, kWidth/5.5, kWidth/5.5)];
    [self.view addSubview:self.imageView];
    [_imageView release];
    
    
    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.imageView.frame.origin.x+self.imageView.frame.size.width+10,self.imageView.frame.origin.y,  kWidth-(self.imageView.frame.origin.x+self.imageView.frame.size.width+10)-5, self.imageView.frame.size.height/2)];
    self.nameLabel.textColor = self.color;

   // self.nameLabel.backgroundColor = [UIColor blueColor];
    [self.view addSubview:self.nameLabel];
    [_nameLabel release];
    
    
    
    self.calLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.nameLabel.frame.origin.x, self.nameLabel.frame.origin.y+self.nameLabel.frame.size.height, kWidth/2/5.5, self.nameLabel.frame.size.height)];
    self.calLabel.textAlignment = NSTextAlignmentCenter;
    self.calLabel.font = [UIFont systemFontOfSize:14];
      self.calLabel.textColor = [UIColor redColor];
    [self.view addSubview:self.calLabel];
    [_calLabel release];
    
    self.appendLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.calLabel.frame.origin.x+self.calLabel.frame.size.width, self.calLabel.frame.origin.y, kWidth/2-self.calLabel.frame.size.width, self.nameLabel.frame.size.height)];
    self.appendLabel.font = [UIFont systemFontOfSize:14];
    self.appendLabel.textColor = self.color;

    [self.view addSubview:self.appendLabel];
    [_appendLabel release];
       self.calButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
       // self.calButton.backgroundColor= [UIColor orangeColor];
    self.calButton.frame = CGRectMake(self.appendLabel.frame.origin.x+self.appendLabel.frame.size.width+10, self.calLabel.frame.origin.y, (kWidth-self.appendLabel.frame.origin.x-self.appendLabel.frame.size.width-10)/2-5, self.calLabel.frame.size.height);
    self.calButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.calButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.calButton setTitle:@"大卡" forState:UIControlStateNormal];
        [self.calButton addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
    self.calButton.tag = 100;
        [self.view addSubview:self.calButton];
        
    self.jouleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.jouleButton.titleLabel.font = [UIFont systemFontOfSize:14];
  //  self.jouleButton.backgroundColor= [UIColor orangeColor];
    self.jouleButton.frame = CGRectMake(self.calButton.frame.origin.x+self.calButton.frame.size.width+5, self.calLabel.frame.origin.y, self.calButton.frame.size.width, self.calLabel.frame.size.height);
    [self.jouleButton setTitle:@"千焦" forState:UIControlStateNormal];
    [self.jouleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.jouleButton.tag = 101;
    [self.jouleButton addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.jouleButton];
    
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(self.calButton.frame.origin.x, self.calButton.frame.origin.y+self.calButton.frame.size.height, self.calButton.frame.size.width, 2)];
    self.lineView.backgroundColor = [UIColor redColor];
    
    [self.view addSubview:self.lineView];
    [_lineView release];
    
    self.collect = [[CollectModel alloc]init];
    
    
    self.array = [NSMutableArray array];
  //  NSLog(@"%@",self.classModel.code);
    
    if (self.number == 0||self.number == 4) {
        self.name = self.classModel.code;
    }else if (self.number == 2){
        self.name = self.carouse.food_code;
    }else if (self.number == 3){

    }
[NewWorking GetDayaWithURL:[NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/%@",self.name] dic:nil sussess:^(id responseObject) {
    
    self.light = responseObject[@"health_light"];
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",responseObject[@"thumb_image_url"]]]placeholderImage:[UIImage imageNamed:@"u=1023456699,842778947&fm=21&gp=0"]];
    self.collect.thumb_image_url = responseObject[@"thumb_image_url"];
    self.nameLabel.text = responseObject[@"name"];
    self.nameLabel.textColor = self.color;
    UIBarButtonItem *leftItemSecond = [[UIBarButtonItem alloc]initWithTitle:responseObject[@"name"] style:UIBarButtonItemStyleDone target:self action:nil];
    self.navigationItem.leftBarButtonItems = @[leftItemFirst,leftItemSecond];

    self.collect.name = responseObject[@"name"];
    self.cal = [responseObject[@"calory"] integerValue];

    

    self.calLabel.text = [NSString stringWithFormat:@"%ld",self.cal];
    
    self.collect.calory = self.cal;
    self.appendLabel.text = @"大卡/100克(可食用部分)";
    self.appendLabel.textColor = self.color;

    self.assess = responseObject[@"appraise"];

    self.collect.code = self.name;
    
    [self.collect release];
    NSLog(@"🐌%@",self.collect.code);
        self.YN =  [[DataBaseHandle shareDataBaseHandle]select:self.collect];
    
    NSLog(@"🐌%d",self.YN);
    if (self.YN) {
       self.rightItem= [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_star-3"] style:UIBarButtonItemStylePlain target:self action:@selector(collectAction:)];
        
        self.navigationItem.rightBarButtonItem = self.rightItem;

    }else{
    self.rightItem= [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_star-1"] style:UIBarButtonItemStylePlain target:self action:@selector(collectAction:)];
        
        self.navigationItem.rightBarButtonItem = self.rightItem;
    }
    
    

  //  NSLog(@"%@",self.assess);
    
    
    
    self.classes = [[ClassModel alloc]init];
    
    [self.classes setValuesForKeysWithDictionary:responseObject];
    
    [_classes release];
    
    
    
    NSArray *keys = @[@"calory",@"protein",@"fat",@"carbohydrate",@"fiber_dietary",@"vitamin_a",@"vitamin_c",@"vitamin_e",@"carotene",@"thiamine",@"lactoflavin",@"niacin",@"cholesterol",@"magnesium",@"calcium",@"iron",@"zinc",@"copper",@"manganese",@"kalium",@"phosphor",@"natrium",@"selenium"];
   // NSLog(@"🍎%@",keys);
    for (int i = 0; i<keys.count; i++) {
        NSString *string = [responseObject[@"ingredient"] objectForKey:keys[i]];
        
        [self.array addObject:string];
    }
  //  NSLog(@"🍎%@",self.array);
    self.titles = @[@"热量",@"蛋白质",@"脂肪",@"碳水化合物",@"膳食纤维",@"维生素A",@"维生素C",@"维生素E",@"胡萝卜素",@"维生素B1",@"维生素B2",@"烟酸",@"胆固醇",@"镁",@"钙",@"铁",@"锌",@"铜",@"锰",@"钾",@"磷",@"钠",@"硒"];
    
    self.calory = [responseObject[@"lights"] objectForKey:@"calory"];
    self.protein =[responseObject[@"lights"] objectForKey:@"protein"];
    self.fat =[responseObject[@"lights"] objectForKey:@"fat"];
    self.carbohydrate =[responseObject[@"lights"] objectForKey:@"carbohydrate"];
    self.fiber_dietary =[responseObject[@"lights"] objectForKey:@"fiber_dietary"];

    
    self.gram =[NSMutableArray arrayWithObjects:@"大卡",@"克",@"克",@"克",@"克",@"微克",@"毫克",@"毫克",@"微克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"微克", nil];
     self.inforView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.imageView.frame.origin.y+self.imageView.frame.size.height+10, kWidth, kHeight-(self.imageView.frame.origin.y+self.imageView.frame.size.height+10)) style:UITableViewStylePlain];
    self.inforView.backgroundColor = [UIColor clearColor];

    self.inforView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.inforView.dataSource = self;
    self.inforView.delegate = self;
    self.inforView.bounces = NO;
    self.inforView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.inforView];
    [_inforView release];
    
    [self.inforView registerClass:[AssessTableViewCell class] forCellReuseIdentifier:@"assess"];
[self.inforView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:@"content"];
    [self.inforView registerClass:[LookTableViewCell class] forCellReuseIdentifier:@"look"];
    [self.inforView reloadData];
    self.calNumber = 1;

} filed:^(NSError *error) {
    NSLog(@"%@",error);
}];


   
}

-(void)collectAction:(UIBarButtonItem *)item
{
    NSLog(@"%d",self.YN);
    
    if (self.YN) {
        
        [self alertForDelete];
        
        
    }else{
        [[DataBaseHandle shareDataBaseHandle]insertCollect:self.collect];
        
        item.image = [UIImage imageNamed:@"icon_star-3"];
        
        [self alertForContent];
        
        self.YN = YES;
    }
    
   
    
   
}

-(void)alertForDelete{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否取消收藏" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"3");
        [[DataBaseHandle shareDataBaseHandle]deleteWithCode:self.collect.code];
        self.rightItem.image = [UIImage imageNamed:@"icon_star-1"];

        self.YN = NO;

    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"6");
        
        [alert dismissViewControllerAnimated:YES completion:^{
            
            
        }];
        
    }];
    
    [alert addAction:okAction];
    
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:^{
        NSLog(@"9");
    }];

    
}


-(void)alertForContent{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alert animated:YES completion:^{
        
            [alert dismissViewControllerAnimated:YES completion:^{
                
                
            }];
        }];
    
}


-(void)backAction:(UIBarButtonItem *)item{
    NSLog(@"🐌%ld",self.number);
    if(self.number == 2||self.number == 1||self.number == 4){
        [self.navigationController popViewControllerAnimated:YES];
        self.navigationController.navigationBarHidden = YES;
        NSLog(@"🍍");
    }else if(self.number == 0||self.number == 3){
        [self.navigationController popViewControllerAnimated:YES];

    }
    
    
}

//跳转元素界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==2) {
        
        MoreInforViewController *infor = [[MoreInforViewController alloc]init];
        infor.array = self.array;
        infor.titles = self.titles;
        infor.gram = self.gram;
        infor.calory = self.calory;
        infor.protein = self.protein;
        infor.fat = self.fat;
        infor.carbohydrate = self.carbohydrate;
        infor.fiber_dietary = self.fiber_dietary;
        
        [self.navigationController pushViewController:infor animated:YES];
        
        [infor release];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 5;
    }else
    {
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        AssessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"assess"];
    
    cell.classModel = self.classes;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }if (indexPath.section == 1) {
        ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"content"];
        cell.labelOne.text = self.titles[indexPath.row];
        cell.labelTwo.text =[NSString stringWithFormat:@"%@%@",self.array[indexPath.row], self.gram[indexPath.row]];
        if ([self.array[indexPath.row] isEqualToString:@""]) {
            cell.labelTwo.text = @"--";
        }
        if (indexPath.row == 0) {
            cell.labelThree.text = self.calory;
        }else if (indexPath.row == 1)
        {
            cell.labelThree.text = self.protein;
            
        }else if (indexPath.row == 2)
        {
            cell.labelThree.text = self.fat;

        }else if (indexPath.row == 3)
        {
            cell.labelThree.text = self.carbohydrate;
            
        }else if (indexPath.row == 4)
        {
            cell.labelThree.text = self.fiber_dietary;
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else{
        LookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"look"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }
    
    
     
     
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
         CGFloat result = [AssessTableViewCell heightOfSelfSuit:self.classes.appraise font:[UIFont systemFontOfSize:17] width:200];
        
        //计算一行文字高度
//        CGFloat singleHeight =[ AssessTableViewCell heightOfSelfSuit:@"s" font:[UIFont systemFontOfSize:17] width:200];
    if (result == [UIScreen mainScreen].bounds.size.width/5.5*1.5+10) {
        return [UIScreen mainScreen].bounds.size.width/5.5*1.5+10+10;
    }else{
        return result+10;
    
    }
    

    }else{
        return 44;
    }
        
        
        
               
        
   
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
       
        return @"评价";
    }else if(section == 1){
        return @"营养元素(每100克)";
    }else{
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 44;
    }else if (section == 1){
        return 44;
    }else
    {
        return 0;
    }
}

//点击按钮换单位
-(void)changeAction:(UIButton *)button
{
    if (self.calNumber == 0) {
        return;
    }
        if (button.tag == 100) {
        self.lineView.frame = CGRectMake(self.calButton.frame.origin.x, self.calButton.frame.origin.y+self.calButton.frame.size.height, self.calButton.frame.size.width, 2);
        [self.calButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.jouleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        self.calLabel.text = [NSString stringWithFormat:@"%ld", self.cal];
        self.appendLabel.text = @"大卡/100克(可食用部分)";
        [self.array replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"%ld",self.cal]];
        [self.gram replaceObjectAtIndex:0 withObject:@"大卡"];

        [self.inforView reloadData];
        
    }else{
        self.lineView.frame = CGRectMake(self.jouleButton.frame.origin.x, self.calButton.frame.origin.y+self.calButton.frame.size.height, self.calButton.frame.size.width, 2);
        [self.calButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.jouleButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        
        self.calLabel.text = [NSString stringWithFormat:@"%d", (int)(self.cal *4.186)];
        self.appendLabel.text = @"千焦/100克(可食用部分)";
        [self.array replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"%d",(int)(self.cal *4.186)]];
        [self.gram replaceObjectAtIndex:0 withObject:@"千焦"];
        [self.inforView reloadData];
    }

        
    
}
- (BOOL)prefersStatusBarHidden{
    NSLog(@"ne");
    return NO;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
